<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <van-cell
        v-for="(item, index) in list"
        :key="index"
        :title="item.title"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from "@/api/search";
export default {
  name: "SearchResult",
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 10,
      error: false,
    };
  },
  methods: {
    async onLoad() {
      try {
        // 异步更新数据
        const { data } = await getSearchResult({
          page: this.page, //页数，不传默认为1
          per_page: this.perPage, //每页数量，不传每页数量由后端决定
          q: this.searchText, //搜索关键词
        });
        const res = data.data.results;
        this.list.push(...res);
        // 加载状态结束
        this.loading = false;

        // 数据全部加载完成
        if (res.length) {
          this.page++;
        } else {
          this.finished = true;
        }
      } catch (err) {
        // 错误提示
        this.error = true;
        this.loading = false;
      }
    },
  },
};
</script>

<style>
</style>